package vip.xiaonuo.modular.reactor;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reactor.core.Reactor;
import reactor.event.Event;
import reactor.function.Consumer;
import vip.xiaonuo.core.exception.ServiceException;
import vip.xiaonuo.facedoor.modular.memberuser.entity.MemberUser;
import vip.xiaonuo.facedoor.modular.memberuser.service.MemberUserService;
import vip.xiaonuo.facedoor.modular.topic.EventTopic;
import vip.xiaonuo.facedoor.modular.visitor.entity.Visitor;
import vip.xiaonuo.facedoor.modular.visitor.service.VisitorService;
import vip.xiaonuo.modular.remoteapi.stairs.RemoteStairsConstant;
import vip.xiaonuo.modular.sync.DeviceEvent;
import vip.xiaonuo.modular.ybuildingmemberrl.entity.YBuildingMemberRl;
import vip.xiaonuo.modular.ybuildingmemberrl.mapper.YBuildingMemberRlMapper;
import vip.xiaonuo.modular.ybuildingmemberrl.param.YBuildingMemberRlParam;
import vip.xiaonuo.modular.ybuildingvisitorrl.entity.YBuildingVisitorRl;
import vip.xiaonuo.modular.ybuildingvisitorrl.mapper.YBuildingVisitorRlMapper;
import vip.xiaonuo.modular.ybuliding.entity.YBuliding;
import vip.xiaonuo.modular.ybuliding.service.YBulidingService;
import vip.xiaonuo.modular.ydeviceevent.entity.YDeviceEvent;
import vip.xiaonuo.modular.ydeviceevent.mapper.YDeviceEventMapper;
import vip.xiaonuo.modular.yelevatordevice.entity.YElevatorDevice;
import vip.xiaonuo.modular.yelevatordevice.service.YElevatorDeviceService;
import vip.xiaonuo.sys.modular.org.entity.SysOrg;
import vip.xiaonuo.sys.modular.org.service.SysOrgService;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

import static reactor.event.selector.Selectors.$;

/**
 * 访客机新增访客 监听 门禁设备增加
 */
@Service
@Slf4j
public class StatisVisitorMiniAppAddListener implements Consumer<Event<Long>>, InitializingBean {

    @Autowired
    private Reactor reactor;

    @Autowired
    private VisitorService visitorService;

    @Autowired
    private SysOrgService sysOrgService;

    @Resource
    private YBuildingVisitorRlMapper buildingVisitorRlMapper;

    @Autowired
    private MemberUserService memberService;

    @Resource
    private YBuildingMemberRlMapper yBuildingMemberRlMapper;

    @Resource
    private YElevatorDeviceService yElevatorDeviceService;

    @Resource
    private YBulidingService yBulidingService;

//    @Resource
//    private YDeviceEventMapper deviceEventMapper;

    @Override
    public void accept(Event<Long> event) {
        Visitor visitor = visitorService.getById(event.getData());
        if (visitor == null) {
            throw new ServiceException(500, "访客不存在");
        }
        log.info("小程序新增访客 监听 梯控设备增加【{}】", visitor.getName());

        SysOrg sysOrg = sysOrgService.getById(visitor.getCompanyId());
        if (sysOrg == null) {
            throw new ServiceException(500, "找不到被访人公司");
        }

        MemberUser invitorMember = null;
        // 如果邀请人不为null  则使用邀请人的组织
        if (StringUtils.isNotBlank(visitor.getInviterPhone())){
            invitorMember=this.getByPhone(visitor.getInviterPhone());
        }

        // 权限复制
        if (invitorMember != null) {
            copyMemberDevice(visitor, invitorMember);
        } else {
            copyOrgDevice(visitor, sysOrg);
        }
    }

    private void copyOrgDevice(Visitor visitor, SysOrg sysOrg) {
        Long buildingId = sysOrg.getBuildingId();
        YBuliding buliding = yBulidingService.getById(buildingId);
        List<YElevatorDevice> devices = yElevatorDeviceService.list(
                new LambdaQueryWrapper<YElevatorDevice>().eq(YElevatorDevice::getBuildingId, buildingId));
        for (YElevatorDevice device : devices) {
            YBuildingVisitorRl saveBean = new YBuildingVisitorRl();
            saveBean.setDeviceSyncStatus(RemoteStairsConstant.DeviceSyncStatus.SYNC_SUCCESS);
            saveBean.setDeviceId(device.getId());
            saveBean.setVisitorId(visitor.getId());
            saveBean.setBuildingId(buliding.getId());
            saveBean.setBuildingName(buliding.getName());
            saveBean.setDeviceName(device.getName());
            saveBean.setDeviceRole("0");
            saveBean.setVisitorName(visitor.getName());
            saveBean.setHandFloor(sysOrg.getHandFloor());
            saveBean.setLiveFloor(sysOrg.getLiveFloor());
            buildingVisitorRlMapper.insert(saveBean);
//            YDeviceEvent deviceEvent = new YDeviceEvent();
//            deviceEvent.setDeviceNo(device.getDeviceNo());
//            deviceEvent.setStatus(DeviceEvent.NEW);
//            deviceEvent.setSysType(2);
//            deviceEvent.setCreateDate(new Date());
//            deviceEvent.setBody(saveBean.getId().toString());
//            deviceEvent.setType(RemoteStairsConstant.RequestCmd.ADD_PERSON);
//            deviceEventMapper.insert(deviceEvent);
        }
    }

    private void copyMemberDevice(Visitor visitor, MemberUser invitorMember) {
        List<YBuildingMemberRl> buildingMemberRls = yBuildingMemberRlMapper.findList(new YBuildingMemberRlParam().setMemberId(invitorMember.getId()));
        buildingMemberRls.forEach(buildingMemberRl -> {
            // 不允许复制管理员权限
//            if (buildingMemberRl.getDeviceRole().equals("0")) {
                YBuildingVisitorRl saveBean = new YBuildingVisitorRl();
                saveBean.setDeviceSyncStatus(RemoteStairsConstant.DeviceSyncStatus.SYNC_SUCCESS);
                BeanUtils.copyProperties(buildingMemberRl, saveBean);
                saveBean.setId(null);
                saveBean.setVisitorId(visitor.getId());
                buildingVisitorRlMapper.insert(saveBean);
//                YDeviceEvent deviceEvent = new YDeviceEvent();
//                deviceEvent.setDeviceNo(buildingMemberRl.getDeviceNo());
//                deviceEvent.setStatus(DeviceEvent.NEW);
//                deviceEvent.setSysType(2);
//                deviceEvent.setCreateDate(new Date());
//                deviceEvent.setBody(saveBean.getId().toString());
//                deviceEvent.setType(RemoteStairsConstant.RequestCmd.ADD_PERSON);
//                deviceEventMapper.insert(deviceEvent);
//            }
        });
    }

    public MemberUser getByPhone(String tel) {
        return memberService.getOne(new LambdaQueryWrapper<MemberUser>().eq(MemberUser::getTel, tel));
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        reactor.on($(EventTopic.VISITOR_MINIAPP_ADD), this);
    }
}
